package com.finance.view.security;

import com.finance.model.types.UserAccountTypeEnum;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Visual556
 */
public class AuthorizationListener implements PhaseListener {

    public static final String INDEX = "index.xhtml";
    public static final String ADMIN_PREFIX = "/admin/";
    public static final String REGULAR_PREFIX = "/regular/";

    @Override
    public void beforePhase(PhaseEvent pe) {
    }

    @Override
    public void afterPhase(PhaseEvent pe) {
        FacesContext facesContext = pe.getFacesContext();
        ExternalContext externalContext = facesContext.getExternalContext();
        HttpServletRequest servletRequest = (HttpServletRequest) externalContext.getRequest();
        String requestUrl = servletRequest.getRequestURL().toString();
        HttpSession httpSession = (HttpSession) externalContext.getSession(true);

        String username = (String) httpSession.getAttribute("username");
        NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();

        if (!requestUrl.endsWith(INDEX) && (username == null || username.isEmpty())) {
            navigationHandler.handleNavigation(facesContext, null, "index.xhtml");
        } else {
            UserAccountTypeEnum userAccountEnum = (UserAccountTypeEnum) httpSession.getAttribute("userAccountEnum");
            if (requestUrl.contains(ADMIN_PREFIX) && (userAccountEnum == null || userAccountEnum != UserAccountTypeEnum.ADMIN)) {
                navigationHandler.handleNavigation(facesContext, null, "regularNotAdmin");
            }
        }
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }
}
